package com.yantong.controller.product;

import com.yantong.pojo.Category;
import com.yantong.service.CategoryService;
import com.yantong.pojo.Centre;
import com.yantong.service.CentreService;
import com.yantong.annotation.Log;
import com.yantong.constant.CategoryType;
import com.yantong.constant.ProductType;
import com.yantong.controller.BaseController;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.pojo.Dispatch;
import com.yantong.service.DispatchService;
import com.yantong.pojo.ProductCentre;
import com.yantong.pojo.ProductCentreAttribute;
import com.yantong.enums.PropertiesEnum;
import com.yantong.pojo.vo.ProductCentreCostVo;
import com.yantong.pojo.vo.ProductCentreVo;
import com.yantong.pojo.vo.ProductSelectedVo;
import com.yantong.pojo.vo.ProductsReqVo;
import com.yantong.service.ProductAuthorityService;
import com.yantong.service.ProductCentreService;
import com.yantong.pojo.ListMemberParams;
import com.yantong.pojo.Member;
import com.yantong.service.CommanderListService;
import com.yantong.utils.ValidateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商品
 *
 * @author baolingyu
 * @date 2018年8月28日
 */
@Controller
@RequestMapping("/product/centre")
public class ProductCentreController extends BaseController {
	private static final String prefix = "product/centre";

	private Logger logger = LoggerFactory.getLogger(ProductCentreController.class);

	@Autowired
	private CategoryService categoryService;
	@Autowired
	private DispatchService dispatchService;
	@Autowired
	@Lazy
	private ProductCentreService pCentreService;
	@Autowired
	private CommanderListService commanderListService;
	@Autowired
	private CentreService centreService;
	@Autowired
	private ProductAuthorityService productAuthorityService;

	/**
	 * 跳转页面
	 *
	 * @return
	 */
	@GetMapping()
	@RequiresPermissions("product:centre:manage")
	public String products(Model model) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		Map<String, Object> map = getCentreIdModelInfo();
		List<Category> categorys = null;
		//商户
		if (StringUtils.isNotEmpty(map.get("flag").toString()) && (map.get("flag").equals("1") || map.get("flag").equals("6"))) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(new Long(map.get("centreId").toString()));
			categorys = categoryService.getListCategory(category);
		} else if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("0")) {
			categorys = categoryService.listCategorys(0L);
		}
		for (Category category : categorys) {
			if (category.getType() == CategoryType.houtaileimu.getType()) {
				category.setTypeName("活动类目");
			} else if (category.getType() == CategoryType.qiantaileimu.getType()) {
				category.setTypeName("前台类目");
			} else if (category.getType() == CategoryType.houtaileimu.getType()) {
				category.setTypeName("后台类目");
			} else if (category.getType() == CategoryType.zhuyeleimu.getType()) {
				category.setTypeName("主页类目");
			} else if (category.getType() == CategoryType.waimaileimu.getType()) {
				category.setTypeName("外卖类目");
			}
//            else if(category.getType()==CategoryType.tangshileimu.getType()){
//                category.setTypeName("堂食类目");
//            }else if(category.getType()==CategoryType.zitileimu.getType()){
//                category.setTypeName("自提类目");
//            }
		}
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		//判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
		Long teamId = getUserTeamId();
		if (null != teamId) {
			model.addAttribute("teamId", teamId);
			model.addAttribute("liansuoid", teamId);
		}
		model.addAttribute("category", categorys);
		model.addAllAttributes(map);
		return prefix + "/productCentres";
	}


	/**
	 * 跳转页面
	 *
	 * @return
	 */
	@GetMapping("/tospellgroupPage")
	@RequiresPermissions("product:centre:spellgroup")
	public String tospellgroupPage(Model model) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		Map<String, Object> map = getCentreIdModelInfo();
		List<Category> categorys = null;
		//商户
		if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(new Long(map.get("centreId").toString()));
			categorys = categoryService.getListCategory(category);
		} else {
			categorys = categoryService.listCategorys(0L);
		}
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		//判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
		Long teamId = getUserTeamId();
		if (null != teamId) {
			model.addAttribute("teamId", teamId);
		}
		model.addAttribute("category", categorys);
		model.addAllAttributes(map);
		return prefix + "/spellgroup";
	}

	/**
	 * 跳转页面
	 *
	 * @return
	 */
	@GetMapping("/toSeckillPage")
	@RequiresPermissions("product:center:seckill")
	public String toSeckillPage(Model model) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		Map<String, Object> map = getCentreIdModelInfo();
		List<Category> categorys = null;
		//商户
		if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(new Long(map.get("centreId").toString()));
			categorys = categoryService.getListCategory(category);
		} else {
			categorys = categoryService.listCategorys(0L);
		}
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		//判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
		Long teamId = getUserTeamId();
		if (null != teamId) {
			model.addAttribute("teamId", teamId);
		}
		model.addAttribute("category", categorys);
		model.addAllAttributes(map);
		return prefix + "/seckill";
	}

	/**
	 * 跳转页面：预售商品
	 *
	 * @return
	 */
	@GetMapping("/toSpresellPage")
	@RequiresPermissions("product:center:spresell")
	public String toSpresellPage(Model model) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		Map<String, Object> map = getCentreIdModelInfo();
		List<Category> categorys = null;
		//商户
		if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(new Long(map.get("centreId").toString()));
			categorys = categoryService.getListCategory(category);
		} else {
			categorys = categoryService.listCategorys(0L);
		}
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		//判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
		Long teamId = getUserTeamId();
		if (null != teamId) {
			model.addAttribute("teamId", teamId);
		}
		model.addAttribute("category", categorys);
		model.addAllAttributes(map);
		return prefix + "/spresell";
	}

	/**
	 * 跳转页面：预约商品
	 *
	 * @return
	 */
	@GetMapping("/toYuyuePage")
	@RequiresPermissions("product:center:yuyue")
	public String toYuyuePage(Model model) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		Map<String, Object> map = getCentreIdModelInfo();
		List<Category> categorys = null;
		//商户
		if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(new Long(map.get("centreId").toString()));
			categorys = categoryService.getListCategory(category);
		} else {
			categorys = categoryService.listCategorys(0L);
		}
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		//判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
		Long teamId = getUserTeamId();
		if (null != teamId) {
			model.addAttribute("teamId", teamId);
		}
		model.addAttribute("category", categorys);
		model.addAllAttributes(map);
		return prefix + "/yuyue";
	}

	/**
	 * 跳转页面：积分兑换商品
	 *
	 * @return
	 */
	@GetMapping("/toScorePage")
	@RequiresPermissions("product:center:score")
	public String toScorePage(Model model) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		Map<String, Object> map = getCentreIdModelInfo();
		List<Category> categorys = null;
		//商户
		if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(new Long(map.get("centreId").toString()));
			categorys = categoryService.getListCategory(category);
		} else {
			categorys = categoryService.listCategorys(0L);
		}
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		//判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
		Long teamId = getUserTeamId();
		if (null != teamId) {
			model.addAttribute("teamId", teamId);
		}
		model.addAttribute("category", categorys);
		model.addAllAttributes(map);
		return prefix + "/score";
	}


	/**
	 * 跳转商品成本利润表
	 *
	 * @return
	 */
	@GetMapping("/toProductCost")
	@RequiresPermissions("product:centrecost:manage")
	public String toProductCost(Model model) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		model.addAllAttributes(getCentreIdModelInfo());

		Map<String, Object> map = getCentreIdModelInfo();
		List<Category> categorys = null;
		//商户
		if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(new Long(map.get("centreId").toString()));
			categorys = categoryService.getListCategory(category);
		} else {
			categorys = categoryService.listCategorys(0L);
		}
		model.addAttribute("category", categorys);
		model.addAllAttributes(map);
		return prefix + "/productCentresCost";
	}

	/**
	 * 列表
	 *
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-上午11:41:11
	 */
	@GetMapping("/list")
	@ResponseBody
	@RequiresPermissions("product:centre:manage")
	public PageUtils<ProductCentre> list(int offset, int limit, ProductsReqVo productsReqVo) {
		return pCentreService.listCentreProducts(offset, limit, productsReqVo);
	}

	/**
	 * 得到商品利润表
	 */
	@GetMapping("/getProductCentreCostVo")
	@ResponseBody
	@RequiresPermissions("product:centrecost:manage")
	public PageUtils<ProductCentreCostVo> getProductCentreCostVo(int offset, int limit, ProductsReqVo productsReqVo) {
		if (productsReqVo.getLiansuoid() == null) {
			productsReqVo.setLiansuoid(getUserTeamId());
		}
		if (productsReqVo.getCentreId() == null) {
			productsReqVo.setCentreId(getUserCentreId());
		}
		return pCentreService.getProductCentreCostVo(offset, limit, productsReqVo);
	}

	/**
	 * 后台商户商品列表
	 *
	 * @param offset
	 * @param limit
	 * @param vo
	 * @return
	 * @author baolingyu
	 * @date 2018年9月21日-下午5:19:48
	 */
	@GetMapping("/productCentrelist")
	@ResponseBody
	@RequiresPermissions("product:centre:manage")
	public PageUtils<ProductCentre> list(int offset, int limit, ProductCentreVo vo, String idOrName) {
		Long centreId = getUserCentreId();
		if (centreId != null) {
			vo.setCentreId(centreId);
		}
		Long teamId = getUserTeamId();
		if (teamId != null) {
			vo.setLiansuoid(teamId);
		}
		return pCentreService.listCentreProducts(offset, limit, vo, idOrName);
	}

	/**
	 * 跳转到选择商品页面，这里是选择商品库商品
	 *
	 * @return
	 * @author baolingyu
	 * @date 2018年10月17日-下午6:00:43
	 */
	@GetMapping("/toSelectProduct")
	@RequiresPermissions("product:centre:add")
	public String toSelectProduct(Model model) {
		model.addAllAttributes(getCentreIdModelInfo());
		return prefix + "/select_product";
	}

	/**
	 * 跳转到选择商品页面，这里是选择自己商户商品,用于直播、评论中的选择商品
	 *
	 * @return
	 * @author baolingyu
	 * @date 2018年10月17日-下午6:00:43
	 */
	@GetMapping("/toSelectProductFromCentre")
	@RequiresPermissions("product:centre:add")
	public String toSelectProductFromCentre() {
		return prefix + "/select_product1";
	}

	/**
	 * 从商品库选择商品
	 *
	 * @param vo
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-上午11:41:19
	 */
	@RequiresPermissions("product:centre:add")
	@PostMapping("/save")
	@ResponseBody
	public ResultVo save(@RequestBody ProductSelectedVo vo) {
		if (vo == null) {
			return ResultVo.error();
		}

		List<Long> centreIds = vo.getCentreIds();
		if (CollectionUtils.isEmpty(centreIds)) {
			return ResultVo.error("商户为空");
		}
		List<String> ids = vo.getSelectProductIds();

		List<Long> productIds = new ArrayList<>();
		for (String id : ids) {
			productIds.add(Long.valueOf(id));
		}
		for (Long centreId : centreIds) {
			if (pCentreService.save(productIds, centreId, getUserTeamId()) < 1) {
				return ResultVo.error();
			}
		}


		return ResultVo.ok();
	}


	/**
	 * 跳转新增页面
	 *
	 * @param model
	 * @return
	 * @author baolingyu
	 * @date 2018年9月2日-下午12:48:55
	 */
	@RequiresPermissions("product:centre:add")
	@GetMapping("/toAdd")
	public String toAdd(Model model) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		List<Category> categorys = null;
		//商户
		if (getUserCentreId() != null) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(getUserCentreId());
			categorys = categoryService.getListCategory(category);
		} else {
			categorys = categoryService.listCategorys(0L);
		}
		model.addAttribute("category", categorys);

		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		//判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
		Long teamId = getUserTeamId();
		Long centreId = getUserCentreId();
		if (null != teamId) {
			model.addAttribute("teamId", teamId);
		}

//		boolean bol = getZbFlag();
		model.addAttribute("mallCodeFlag", false);

		model.addAttribute("dispatch", dispatchService.getDispatchList(null, 0, centreId, teamId));
		if (getUserCentreId()==null || getUserCentreId().equals(311L)) {
			model.addAttribute("flag", 1);
		} else {
			model.addAttribute("flag", 0);
		}
		return prefix + "/add";
	}

	/**
	 * 商户新增商品
	 *
	 * @param vo
	 * @return
	 * @author baolingyu
	 * @date 2018年9月27日-下午7:46:51
	 */
	@Log(module = "商品管理", operation = "新增商户商品")
	@RequiresPermissions("product:centre:add")
	@PostMapping("/add")
	@ResponseBody
	public ResultVo add(@RequestBody ProductCentreVo vo) {
		if (vo == null) {
			return ResultVo.error();
		}

		Long centreId = getUserCentreId();
		if (centreId == null) {
			return ResultVo.error("该权限属于商户，您无权操作");
		}

		if(vo.getFreeShipping() != null && vo.getFreeShipping().equals(2) && !vo.getProductType().equals(ProductType.WaiMai.getType()) ){
			Dispatch dispatch = dispatchService.getByKey(vo.getDispatchid());
			if (dispatch == null){
				return ResultVo.error("没有对应的邮费模板!");
			}else if(!vo.getLiansuoid().equals(dispatch.getTeamId())){
				return ResultVo.error("该邮费模板归属门店与此商品不一致,请重新选择!");
			}
		}

		if (vo.getId() == null) {
			if (pCentreService.add(vo, centreId) < 1) {
				return ResultVo.error();
			}
		} else if (pCentreService.update(vo) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok(vo.getId() + "");
	}

	/**
	 * 跳转到编辑页面
	 *
	 * @param id
	 * @param model
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:12:57
	 */
	@RequiresPermissions("product:centre:edit")
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable Long id, Model model) {
		Long centreId = getUserCentreId();
		ListMemberParams listMemberParams = new ListMemberParams();
		if (centreId != null) {
			listMemberParams.setCentreId(centreId);
		}
		Map<String, Object> map = getCentreIdModelInfo();
		List<Category> categorys = null;
		//商户
		if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(new Long(map.get("centreId").toString()));
			categorys = categoryService.getListCategory(category);
		} else {
			categorys = categoryService.listCategorys(0L);
		}
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		//判断连锁店ID是否存在，不存在，表示是商户超级管理员账号
		Long teamId = getUserTeamId();
		if (null != teamId) {
			model.addAttribute("teamId", teamId);
		}
//		boolean bol = getZbFlag();

		ProductCentreAttribute productCentreAttribute = pCentreService.getProductCentreAttributeByPcId(id);
		if( productCentreAttribute == null ){
			productCentreAttribute = new ProductCentreAttribute();
		}
		model.addAttribute("productCentreAttribute", productCentreAttribute);
		model.addAttribute("mallCodeFlag", false);
		model.addAttribute("obj", categoryService.getByKey(id));
		model.addAttribute("product", pCentreService.getByKey(id));
		model.addAttribute("dispatch", dispatchService.getDispatchList(null, 0, centreId, teamId));
		model.addAttribute("category", categorys);
		model.addAllAttributes(map);
		Long userCentreId = getUserCentreId();
		if ( userCentreId != null && userCentreId.equals(311L)) {
			model.addAttribute("jllFlag", 1);
		} else {
			model.addAttribute("jllFlag", 0);
		}
		return prefix + "/edit";
	}

	/**
	 * 跳转到设置权限页面
	 *
	 * @param id
	 * @param model
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:12:57
	 */
	@RequiresPermissions("product:centre:edit")
	@GetMapping("/installAuthority/{id}")
	public String installAuthority(@PathVariable Long id, Model model) {
		Long centreId = getUserCentreId();
		model.addAttribute("productAuthorityList", productAuthorityService.listByAll());
		model.addAttribute("product", pCentreService.getByKey(id));
		return prefix + "/installAuthority";
	}

	/**
	 * 更新
	 *
	 * @param vo
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:13:49
	 */
	@Log(module = "商品管理", operation = "编辑商户商品")
	@RequiresPermissions("product:centre:edit")
	@PostMapping("/update")
	@ResponseBody
	public ResultVo update(@RequestBody ProductCentreVo vo) {
		if (vo == null) {
			return ResultVo.error();
		}

		Long centreId = getUserCentreId();
		ProductCentre productCentre = pCentreService.getByKey(vo.getId());
		if (null != centreId && productCentre.getCentreId() != centreId.longValue()) {
			return ResultVo.error("商户只能编辑自己的产品，您无权操作");
		}

		Long teamId = getUserTeamId();
		if (null != teamId && productCentre.getLiansuoid() != teamId.longValue()) {
			return ResultVo.error("门店账号只能编辑该门店的产品，您无权操作");
		}

		if(vo.getFreeShipping().equals(2)){
			Dispatch dispatch = dispatchService.getByKey(vo.getDispatchid());
			if (dispatch == null){
				return ResultVo.error("没有对应的邮费模板!");
			}else if(!vo.getLiansuoid().equals(dispatch.getTeamId())){
				return ResultVo.error("该邮费模板归属门店与此商品不一致,请重新选择!");
			}
		}

		vo.setCentreId(centreId);
		if (pCentreService.update(vo) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 编辑操作
	 * @param productCentre
	 * @return
	 */
	@Log(module = "商品管理", operation = "编辑")
	@ResponseBody
	@RequiresPermissions("product:centre:edit")
	@PostMapping("/updateAuthority")
	public ResultVo updateAuthority(ProductCentre productCentre) {
		if (productCentre == null || productCentre.getId() == null) {
			return ResultVo.error();
		}
		if (pCentreService.updateProductCenter(productCentre) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 列表点击button，更新商品
	 *
	 * @return
	 * @author baolingyu
	 * @date 2018年10月8日-下午9:36:40
	 */
	@Log(module = "商品管理", operation = "商品列表点击button，更新商品")
	@RequiresPermissions("product:centre:edit")
	@PostMapping("/btnUpdate")
	@ResponseBody
	public ResultVo btnUpdate(Long id, String column) {
		if (id == 0 || id == null) {
			return ResultVo.error();
		}

		if (pCentreService.btnUpdate(id, column) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 删除
	 *
	 * @param id
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:20:00
	 */
	@Log(module = "商品管理", operation = "删除商户商品")
	@RequiresPermissions("product:centre:remove")
	@PostMapping("/remove")
	@ResponseBody
	public ResultVo remove(Long id) {
		if (id == null) {
			return ResultVo.error();
		}
		if (pCentreService.remove(id) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:20:00
	 */
	@Log(module = "商品管理", operation = "批量删除商户商品")
	@RequiresPermissions("product:centre:remove")
	@PostMapping("/batchRemove")
	@ResponseBody
	public ResultVo batchRemove(@RequestParam("ids[]") Long[] ids) {
		if (ids == null || ids.length < 1) {
			return ResultVo.error();
		}
		for (Long id : ids) {
			if (pCentreService.remove(id) < 1) {
				return ResultVo.error();
			}
		}
		return ResultVo.ok();
	}

	/**
	 * 复制
	 *
	 * @param id
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:20:00
	 */
	@RequiresPermissions("product:centre:remove")
	@PostMapping("/copy")
	@ResponseBody
	public ResultVo copy(Long id, String centerId, String teamId, Integer productType) {
		if (id == null) {
			return ResultVo.error();
		}
		if (pCentreService.copyProductCentre(id, centerId, teamId, productType) < 1) {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}

	/**
	 * 批量复制
	 *
	 * @param ids
	 * @return
	 * @author baolingyu
	 * @date 2018年8月28日-下午2:20:00
	 */
	@RequiresPermissions("product:centre:remove")
	@PostMapping("/copyBatch")
	@ResponseBody
	public ResultVo copyBatch(@RequestParam("ids[]") Long[] ids, String centerId, String teamId, Integer productType) {
		if (ids == null || ids.length <= 0) {
			return ResultVo.error();
		}
		for (Long id : ids) {
			pCentreService.copyProductCentre(id, centerId, teamId, productType);
		}
		return ResultVo.ok();
	}

	/**
	 * 商品详情，带规格+规格属性+sku
	 *
	 * @param id
	 * @return
	 * @author baolingyu
	 * @date 2018年9月18日-下午4:06:50
	 */
	@RequiresPermissions("product:centre:edit")
	@GetMapping("/detail")
	@ResponseBody
	public ProductCentreVo detail(Long id) {
		return pCentreService.detail(id);
	}

	/**
	 * 更新库存
	 *
	 * @param id
	 * @param total
	 * @return
	 * @author baolingyu
	 * @date 2018年10月15日-下午2:13:47
	 */
	@Log(module = "商品管理", operation = "更新商户商品库存")
	@RequiresPermissions("product:centre:edit")
	@PostMapping("/updateTotal")
	@ResponseBody
	public ResultVo updateTotal(Long id, int total) {
		if (id == 0 || id == null) {
			return ResultVo.error();
		}

		try {
			if (pCentreService.updateTotal(id, total) < 1) {
				return ResultVo.error();
			}
		} catch (Exception e) {
			return ResultVo.error(e.getMessage());
		}
		return ResultVo.ok();
	}

	/**
	 * 更新排序
	 *
	 * @param id
	 * @param displayorder
	 * @return
	 * @author baolingyu
	 * @date 2018年10月15日-下午2:13:47
	 */
	@Log(module = "商品管理", operation = "更新商户商品排序")
	@RequiresPermissions("product:centre:edit")
	@PostMapping("/updateDisplayorder")
	@ResponseBody
	public ResultVo updateDisplayorder(Long id, Integer displayorder) {
		if (id == 0 || id == null) {
			return ResultVo.error();
		}

		try {
			if (pCentreService.updateDisplayorder(id, displayorder) < 1) {
				return ResultVo.error();
			}
		} catch (Exception e) {
			return ResultVo.error(e.getMessage());
		}
		return ResultVo.ok();
	}


	/**
	 * 跳转到详情页，只有查看
	 *
	 * @param id
	 * @param model
	 * @return
	 * @author baolingyu
	 * @date 2018年11月23日-下午9:31:51
	 */
	@RequiresPermissions("product:centre:edit")
	@GetMapping("/detailReadonly/{id}")
	public String detailReadonly(@PathVariable Long id, Model model) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		Map<String, Object> map = getCentreIdModelInfo();
		List<Category> categorys = null;
		//商户
		if (StringUtils.isNotEmpty(map.get("flag").toString()) && map.get("flag").equals("1")) {
			Category category = new Category();
			category.setParentid(0L);
			category.setCentreId(new Long(map.get("centreId").toString()));
			categorys = categoryService.getListCategory(category);
		} else {
			categorys = categoryService.listCategorys(0L);
		}
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());

		Long centreId = getUserCentreId();
		Long teamId = getUserTeamId();

//		boolean bol = getZbFlag();
		model.addAttribute("mallCodeFlag", false);

		ProductCentreAttribute productCentreAttribute = pCentreService.getProductCentreAttributeByPcId(id);
		if( productCentreAttribute == null ){
			productCentreAttribute = new ProductCentreAttribute();
		}
		model.addAttribute("productCentreAttribute", productCentreAttribute);
		model.addAttribute("teams", teams);
		model.addAttribute("obj", categoryService.getByKey(id));
		model.addAttribute("product", pCentreService.getByKey(id));
		model.addAttribute("dispatch", dispatchService.getDispatchList(null, 0, centreId, teamId));
		model.addAttribute("category", categorys);
		model.addAllAttributes(map);
		return prefix + "/detail";
	}

	/**
	 * 商品列表排序更改
	 */
	@Log(module = "商品管理", operation = "更新商户商品列表排序")
	@RequiresPermissions("product:centre:edit")
	@PostMapping("/updateSort")
	@ResponseBody
	public ResultVo updateSort(@RequestBody ProductCentreVo listProduct) {
		//获取页面的参数 整个商品修改的序号，跟商品Id
		if (listProduct.getListProduct().size() > 0) {
			//每个排序进行单一修改，保证批有些数据有问题时不影响其他操作
			listProduct.getListProduct().forEach(Product -> {
				pCentreService.updateSort(Product);
			});
		} else {
			return ResultVo.error();
		}
		return ResultVo.ok();
	}


	/**
	 * 导出商品成本利润表
	 *
	 * @param response
	 * @param productsReqVo
	 */
	@RequiresPermissions("flowLine:manage:wDian")
	@GetMapping("/exportWdians")
	public void exportWdians(HttpServletResponse response, ProductsReqVo productsReqVo) {
		String[] head = {"序号", "商品id", "商品名称", "商品规格", "销售数量", "成本", "商品单价", "销售金额",
				"平台总成本", "平台销售总额", "销售比率", "平台销售利润", "平台利润率", "单品利润",
				"产品利润率", "单品利率占比", "供应商", "买手(采购人)"};
		List<List<Object>> resultData = new ArrayList<>();
		resultData.add(0, Arrays.asList(head));
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("strDt", productsReqVo.getStrDt());
		map.put("endDt", productsReqVo.getEndDt());
		map.put("title", productsReqVo.getTitle());
		map.put("supid", productsReqVo.getSupid());
		map.put("centreId", productsReqVo.getCentreId());
		//得到商品利润表
		List<ProductCentreCostVo> list = pCentreService.getProductCentreCostVoData(map);

		BigDecimal placostprice = null;
		BigDecimal plapricetotal = null;
		BigDecimal plasalespro = null;
		if (pCentreService.getPlacostprice(map) != null) {
			placostprice = new BigDecimal(pCentreService.getPlacostprice(map));//平台总成本
		}
		if (pCentreService.getPlapricetotal(map) != null) {
			plapricetotal = new BigDecimal(pCentreService.getPlapricetotal(map));//平台销售总额
		}
		if (placostprice != null && plapricetotal != null) {
			plasalespro = new BigDecimal(plapricetotal.subtract(placostprice).toString());//平台销售利润
		}

		for (ProductCentreCostVo productCentreCostVo : list) {
			map.put("productId", productCentreCostVo.getProductId());
			ProductCentreCostVo vo = pCentreService.getProductCentreById(map);
			if (vo == null) {

			} else {
				productCentreCostVo.setGrandtotal(vo.getGrandtotal());
				productCentreCostVo.setPricetotal(vo.getPricetotal());
				productCentreCostVo.setProductpro(vo.getProductpro());
			}
		}
		for (ProductCentreCostVo productCentreCostVo : list) {
			//添加平台总成本
			if (placostprice != null) {
				productCentreCostVo.setPlacostprice(placostprice.toString());
			}
			//添加平台销售总额
			if (plapricetotal != null) {
				productCentreCostVo.setPlapricetotal(plapricetotal.toString());
			}
			//设置销售比率
			if (productCentreCostVo.getPricetotal() != null && plapricetotal != null) {
				productCentreCostVo.setSalesrat(new BigDecimal(productCentreCostVo.getPricetotal()).divide(plapricetotal, 5, RoundingMode.HALF_UP).toString());
			}
			if (plasalespro != null) {
				productCentreCostVo.setPlasalespro(plasalespro.toString());//平台销售利润
			}
			//设置平台利润率
			if (plasalespro != null && plapricetotal != null) {
				productCentreCostVo.setPlapromar(plasalespro.divide(plapricetotal, 5, RoundingMode.HALF_UP).toString());
			}

			//设置单品利润率
			if (productCentreCostVo.getProductpro() != null && productCentreCostVo.getPricetotal() != null) {
				productCentreCostVo.setProductpromar((new BigDecimal(productCentreCostVo.getProductpro()).divide(new BigDecimal(productCentreCostVo.getPricetotal()), 5, RoundingMode.HALF_UP)).toString());
			}
			//设置单品利润占比
			if (productCentreCostVo.getProductpro() != null && plasalespro != null) {
				productCentreCostVo.setProductpor(new BigDecimal(productCentreCostVo.getProductpro()).divide(plasalespro, 5, RoundingMode.HALF_UP).toString());
			}

		}

		for (int i = 0; i < list.size(); i++) {
			ProductCentreCostVo productCentreCostVo = list.get(i);
			List<Object> row = new ArrayList<>();
			row.add(i + 1);
			row.add(productCentreCostVo.getId());
			row.add(productCentreCostVo.getTitle());
			row.add(productCentreCostVo.getUnit());
			row.add(productCentreCostVo.getGrandtotal() == null ? 0 : productCentreCostVo.getGrandtotal());
			row.add(productCentreCostVo.getCostprice() == null ? 0 : productCentreCostVo.getCostprice());
			row.add(productCentreCostVo.getMarketprice() == null ? 0 : productCentreCostVo.getMarketprice());
			row.add(productCentreCostVo.getPricetotal() == null ? 0 : productCentreCostVo.getPricetotal());
			row.add(productCentreCostVo.getPlacostprice() == null ? 0 : productCentreCostVo.getPlacostprice());
			row.add(productCentreCostVo.getPlapricetotal() == null ? 0 : productCentreCostVo.getPlapricetotal());
			row.add(productCentreCostVo.getSalesrat() == null ? 0 : productCentreCostVo.getSalesrat());
			row.add(productCentreCostVo.getPlasalespro() == null ? 0 : productCentreCostVo.getPlasalespro());
			row.add(productCentreCostVo.getPlapromar() == null ? 0 : productCentreCostVo.getPlapromar());
			row.add(productCentreCostVo.getProductpro() == null ? 0 : productCentreCostVo.getProductpro());
			row.add(productCentreCostVo.getProductpromar() == null ? 0 : productCentreCostVo.getProductpromar());
			row.add(productCentreCostVo.getProductpor() == null ? 0 : productCentreCostVo.getProductpor());
			row.add(productCentreCostVo.getSupname() == null ? "未定义" : productCentreCostVo.getSupname());
			row.add(productCentreCostVo.getPurchaser() == null ? "未定义" : productCentreCostVo.getPurchaser());
			resultData.add(row);
		}
		String fileName = "商品成本利润表" + DateUtils.format(new Date(), "yyyy/MM/dd/ HH:mm:ss");
		try {
			ExcelHelper.exportExcel(response, fileName, "商品成本利润表", resultData);
		} catch (IOException e) {
			logger.info("export member error:{}", e.getMessage());
		}

	}


	/**
	 * 导出
	 *
	 * @param vo
	 * @param idOrName
	 * @param response
	 */
	@RequiresPermissions("product:centre:exportProductCentre")
	@GetMapping("/exportProductCentre")
	public void exportProductCentre(ProductCentreVo vo, String idOrName, HttpServletResponse response) {
		List<List<Object>> resultData = new ArrayList<>();
		String[] head = {"序号", "ID", "排序", "商品名称", "单位", "商品属性",
				"上架时间", "下架时间", "开售时间", "停售时间", "现价", "市场价", "成本价", "门店佣金", "销量",
				"库存", "状态", "审核状态"};
		resultData.add(0, Arrays.asList(head));

		List<ProductCentre> list = pCentreService.getExportProductCentre(vo, idOrName);
		int flag = 1;
		if (CollectionUtils.isNotEmpty(list)) {
			for (ProductCentre obj : list) {
				if (obj == null) {
					continue;
				}
				String attr = "";
				String status = "";
				if (obj.getStatus() == 1) {
					status = "上架";
				}
				if (obj.getStatus() == 0) {
					status = "下架";
				}
				if (obj.getStatus() == 2) {
					status = "定时上架";
				}
//                if (obj.getIszhicai() != 0) {
//                    attr = attr.concat("[直采]");
//                }
				if (obj.getIsmao() != 0) {
					attr = attr.concat("[特卖]");
				}
//                if (obj.getIsfanchang() != 0) {
//                    attr = attr.concat("[返场]");
//                }
//                if (obj.getIszhutihuakuang() != 0) {
//                    attr = attr.concat("[主题画框]");
//                }
				if (obj.getIsnew() != 0) {
					attr = attr.concat("[新品]");
				}
//                if (obj.getIsbig() != 0) {
//                    attr = attr.concat("[大件]");
//                }
//                if (obj.getIslimited() != 0) {
//                    attr = attr.concat("[限量]");
//                }
//                if (obj.getIsmiaosha() != 0) {
//                    attr = attr.concat("[秒杀]");
//                }
//                if (obj.getIsvip() != 0) {
//                    attr = attr.concat("[vip]");
//                }
				if (obj.getIshot() != 0) {
					attr = attr.concat("[爆款]");
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				List<Object> row = new ArrayList<>();
				row.add(flag);
				row.add(obj.getId());
				row.add(obj.getDisplayorder());
				row.add(obj.getTitle());
				row.add(obj.getUnit());
				row.add(attr);
				row.add(obj.getUpStartTime() == null ? "" : sdf.format(obj.getUpStartTime()));
				row.add(obj.getUpEndTime() == null ? "" : sdf.format(obj.getUpEndTime()));
				row.add(obj.getTimestart() == null ? "" : sdf.format(obj.getTimestart()));
				row.add(obj.getTimeend() == null ? "" : sdf.format(obj.getTimeend()));
				row.add(obj.getMarketprice());
				row.add(obj.getProductprice());
				row.add(obj.getCostprice());
				row.add(obj.getHeadcommission());
				row.add(obj.getSalesreal());
				row.add(obj.getTotal());
				row.add(status);
				row.add(obj.getAuditing() == 1 ? "审核通过" : "未审核");
				resultData.add(row);
				flag++;
			}
		}
		String fileName = "商户商品_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
		try {
			ExcelHelper.exportExcel(response, fileName, "商户商品", resultData);
		} catch (IOException e) {
			logger.info("export achieve count error:{}", e.getMessage());
		}
	}


	/**
	 * 跳转页面：选择商户页面
	 */
	@GetMapping("/toCentre")
	public String toCentre(Model model, String idDom, String nameDom, Integer singleSelect, String callback) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}

		Map<String, Object> map = getCentreIdModelInfo();
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		model.addAttribute("idDom", idDom);
		model.addAttribute("nameDom", nameDom);
		model.addAttribute("singleSelect", singleSelect);
		model.addAttribute("callback", callback);
		model.addAllAttributes(map);
		return prefix + "/toCentre";
	}

	/**
	 * 跳转页面：选择门店页面
	 */
	@GetMapping("/toStore")
	public String toStore(Model model, String idDom, String nameDom, Integer singleSelect, String callback) {
		ListMemberParams listMemberParams = new ListMemberParams();
		if (getUserCentreId() != null) {
			listMemberParams.setCentreId(getUserCentreId());
		}

		Map<String, Object> map = getCentreIdModelInfo();
		List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
		model.addAttribute("teams", teams);
		model.addAttribute("idDom", idDom);
		model.addAttribute("nameDom", nameDom);
		model.addAttribute("singleSelect", singleSelect);
		model.addAttribute("callback", callback);
		model.addAllAttributes(map);
		return prefix + "/toStore";
	}

	/**
	 * 商户列表数据
	 *
	 * @param name
	 * @param type
	 * @param offset
	 * @param limit
	 * @return
	 */
	@ResponseBody
	@GetMapping("/centreList")
	public PageUtils<Centre> listCentres(String name, String type, int offset, int limit) {
		return centreService.listCentres(getUser(), name, type, "1", offset, limit);
	}

	/**
	 * 门店列表
	 *
	 * @param listMemberParams
	 * @param offset
	 * @param limit
	 * @return
	 */
	@ResponseBody
	@GetMapping("/storeList")
	public PageUtils<Member> listCommanders(ListMemberParams listMemberParams, int offset, int limit) {
		if (listMemberParams.getCentreId() == null) {
			listMemberParams.setCentreId(getUserCentreId());
		}
		return commanderListService.listCommanders(listMemberParams, new Member(), offset, limit);
	}
}
    
